package cn.ulyer.core.config;


import cn.hutool.core.exceptions.ExceptionUtil;
import cn.ulyer.common.constants.ResultCode;
import cn.ulyer.common.exception.BizException;
import cn.ulyer.common.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

@RestControllerAdvice
@Slf4j
public class ExceptionAdvise {

	public ExceptionAdvise(){
		log.info("global exception handler configured");
	}


	@ExceptionHandler(AccessDeniedException.class)
	public Result accessDenied(AccessDeniedException deniedException,HttpServletResponse response){
		response.setStatus(HttpStatus.FORBIDDEN.value());
		return Result.fail(ResultCode.ACCESS_DENIED).message(deniedException.getMessage());
	}

	@ExceptionHandler(value = {NoHandlerFoundException.class})
	public Result notFound(NoHandlerFoundException notFound,HttpServletResponse response){
		response.setStatus(HttpStatus.NOT_FOUND.value());
		return Result.fail(ResultCode.FAILURE).message(notFound.getMessage());
	}

	@ExceptionHandler({AuthenticationException.class, OAuth2Exception.class})
	public Result authException(RuntimeException authenticationException,HttpServletResponse response){
		response.setStatus(HttpStatus.UNAUTHORIZED.value());
		log.error("auth fail :{} ",authenticationException);
		return Result.fail(ResultCode.UNAUTHORIZED).message(authenticationException.getMessage());
	}

	@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
	public Result requestWarning(ServletException e,HttpServletResponse response){
		response.setStatus(HttpStatus.METHOD_NOT_ALLOWED.value());
		return Result.fail(ResultCode.FAILURE).message(e.getMessage());
	}

	@ExceptionHandler({IllegalArgumentException.class, BizException.class})
	public Result argError(RuntimeException e,HttpServletResponse response){
		response.setStatus(HttpStatus.BAD_REQUEST.value());
		log.error("error:{}",e);
		return Result.fail(ResultCode.FAILURE).message(e.getMessage());

	}

	@ExceptionHandler(Exception.class)
	public Result handler(Exception e, HttpServletResponse response){
		response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
		log.error("system  error :{}", ExceptionUtil.stacktraceToString(e));
		return Result.fail(ResultCode.ERROR).message(e.getMessage());
	}



}



